﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.System.Security
{
    [UseDI(ServiceLifetime.Scoped)]
    public class SecurityRepository : Repository<SysSecurity, DefaultDbContext>
    {
        private readonly ILogger logger;

        public SecurityRepository(DefaultDbContext dbContext, IApplicationContext applicationContext, ILogger<SecurityRepository> logger)
            : base(dbContext, applicationContext)
        {
            this.logger = logger;
        }

        public bool UpdateLoginInfoStatus(SysSecurity security, string? loginIp, DateTime loginTime)
        {
            if (security == null)
                return false;
            var sql_update = Sql.Builder;
            sql_update.Append("Update sys_security SET last_login_ip = @0,last_login_time = @1 where security_id = @2", loginIp, loginTime, security.SecurityId);//局部更新数据库
            int affectCount = DbContext.Execute(sql_update);
            if (affectCount > 0)
            {
                security.LastLoginIp = loginIp;
                security.LastLoginTime = loginTime;
                base.OnUpdated(security);//更新内存数据
                return true;
            }
            return false;
        }

        public SysSecurity? GetSysSecurityByOpenId(string openId)
        {
            Sql sql = Sql.Builder.Select("security_id").From("sys_security").Where("open_id=@0", openId);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }
    }
}